<template>
  <div>
    <el-dialog
      :model-value="dialogVisible"
      @close="closeDialog"
      title="营销图设置"
      width="800"
      center
      :close-on-click-modal="false"
    >
      <div class="main" v-loading="loading" element-loading-text="图片处理中">
        <div class="material-view leftdiv" ref="htmlCanvas">
          <div class="capture-wrapper" ref="container">
            <!-- 拖拽 -->
            <DraggableDiv
              contentType="img"
              :container="container"
              v-if="dialogForm.show_id.includes('2')"
            >
              <div v-if="LOGO_URL">
                <img :src="LOGO_URL" class="logo-img" />
                <div class="drag-edit-box">
                  <span class="btn" @click.stop="updateLogo">编辑</span>
                  <el-divider direction="vertical" />
                  <span class="btn" @click.stop="delLogo">删除</span>
                </div>
              </div>
              <div v-else class="zone-logo" @click.stop="updateLogo">
                点击上传机构logo
              </div>
            </DraggableDiv>
            <div id="capture" class="capture-body">
              <!-- 加水印4.8 如果出现这个不显示水印，这样动的目的是不改他之前的 -->

              <template
                v-if="!['https://mcdn.chatgk.com'].includes(backgroundImageUrl)"
              >
                <el-watermark
                  :gap="[10, 10]"
                  rotate="-45"
                  :image="backgroundImageUrl"
                >
                  <img :src="dialogForm.img_url || undefined" />
                </el-watermark>
              </template>

              <!-- 左侧背景图 -->
              <img v-else :src="dialogForm.img_url" />
            </div>

            <!-- 左侧底部信息 -->
            <div class="bottom-info">
              <!-- 用户信息 -->
              <div class="user-info" v-if="dialogForm.show_id.includes('4')">
                <div class="info-box">
                  <span class="text">联系人：</span>
                  <span class="title">{{ dialogForm.contacts || '--' }}</span>
                </div>
                <div class="info-box">
                  <span class="text">联系电话：</span>
                  <span class="title">{{ dialogForm.phone || '--' }}</span>
                </div>
                <div class="info-box">
                  <span class="text">联系地址：</span>
                  <span class="title address">{{
                    dialogForm.address || '--'
                  }}</span>
                </div>
              </div>
              <!-- 前端生成二维码 -->
              <QrcodeGenerator
                :text="qrText"
                :size="70"
                level="H"
                v-if="dialogForm.show_id.includes('3') && !dialogForm.qrcode"
                style="z-index: 99"
                class="code-box"
              />
              <img
                :src="dialogForm.qrcode"
                v-else
                alt=""
                style="z-index: 99"
                class="code-box img"
              />
            </div>
            <!-- 水印图 -->
            <div
              v-if="dialogForm.show_id.includes('1') && 0 > 1"
              :style="backgroundImageStyle"
              class="watermark"
            ></div>
          </div>
        </div>
        <div class="material-edit rightdiv">
          <div class="market-form">
            <el-form :model="form" label-width="120px">
              <el-form-item label="营销图名称">
                <el-input v-model="dialogForm.mg_name" disabled class="dis" />
              </el-form-item>
              <el-form-item label="显示设置">
                <el-checkbox-group v-model="dialogForm.show_id">
                  <el-checkbox value="1" class="block"
                    >水印
                    <span>
                      <el-button
                        class="qrcode-upload"
                        type="primary"
                        v-if="dialogForm.show_id.includes('1')"
                        @click="openUpload('water')"
                      >
                        替换 &nbsp;|
                      </el-button>
                      <el-button
                        class="qrcode-upload"
                        type="primary"
                        v-if="dialogForm.show_id.includes('1')"
                        @click="deleteWatermark"
                      >
                        删除
                      </el-button>
                    </span>
                  </el-checkbox>

                  <el-checkbox value="2" class="block">Logo</el-checkbox>
                  <el-checkbox value="3" style="display: inline-block"
                    >二维码</el-checkbox
                  >
                  <span v-if="dialogForm.show_id.includes('3')">
                    <el-button
                      class="qrcode-upload"
                      v-if="!dialogForm.qrcode"
                      type="primary"
                      @click="openUpload('code')"
                    >
                      上传二维码
                    </el-button>
                    <el-button
                      class="qrcode-upload"
                      type="primary"
                      v-if="dialogForm.qrcode"
                      @click="openUpload('code')"
                    >
                      替换 &nbsp;|
                    </el-button>
                    <el-button
                      class="qrcode-upload"
                      type="primary"
                      v-if="dialogForm.qrcode"
                      @click="deleteQrcode"
                    >
                      删除
                    </el-button>
                  </span>
                  <el-checkbox value="4" class="block">联系信息</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <div v-if="dialogForm.show_id.includes('4')">
                <el-form-item label="联系人">
                  <el-input v-model="dialogForm.contacts" clearable />
                </el-form-item>
                <el-form-item label="联系电话">
                  <el-input v-model="dialogForm.phone" type="tel" clearable />
                </el-form-item>
                <el-form-item label="联系地址">
                  <el-input
                    v-model="dialogForm.address"
                    type="textarea"
                    clearable
                  />
                </el-form-item>
              </div>
            </el-form>
          </div>
          <div class="footer">
            <!-- 通知父组件关闭弹窗 -->
            <el-button type="primary" @click="saveEdit('save')" color="#165dff"
              >保存编辑</el-button
            >
            <el-tooltip
              class="box-item"
              effect="dark"
              content="预览"
              placement="top"
            >
              <el-icon @click="saveEdit('preview')">
                <View />
              </el-icon>
            </el-tooltip>
            <div class="tooltip-container">
              <el-icon @click="downloadImage('water')">
                <Download />
              </el-icon>
              <div class="tooltip-text">
                <span @click="downloadImage('water')">图片</span>
                &nbsp;|&nbsp;
                <span @click="downloadImage('original')">原图</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 上传二维码弹窗 -->
      <el-dialog
        v-model="upload.open"
        width="30%"
        :title="upload.title"
        append-to-body
        @close="closeUploadDialog"
        center
        :close-on-click-modal="false"
      >
        <template #default>
          <el-upload
            class="upload-demo"
            ref="uploadRef"
            :limit="1"
            accept=".jpg,.png"
            drag
            :headers="upload.headers"
            :http-request="customUploadRequest"
          >
            <el-icon class="el-icon--upload">
              <UploadFilled />
            </el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                图片仅支持上传jpg/png格式，且不超过500kb；图片尺寸为360*360
              </div>
            </template>
          </el-upload>
        </template>
        <template #footer>
          <div class="el-dialog__footer">
            <span class="dialog-footer">
              <el-button
                type="primary"
                plain
                @click="submit"
                :disabled="upload.disabled"
                >提交</el-button
              >
              <el-button type="primary" plain @click="closeUploadDialog"
                >关闭弹窗</el-button
              >
            </span>
          </div>
        </template>
      </el-dialog>
    </el-dialog>
    <!-- 裁剪/上传logo -->
    <CropImage
      v-model:isCropperVisible="isCropperVisible"
      :imageUrl="LOGO_URL"
      @crop="crop"
    />
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { getToken } from '@/utils/auth';
import {
  uploadFile,
  saveMarketingGallery,
  addDownloadNum,
} from '@/api/serviceCenter';
import { ElMessageBox } from 'element-plus';
import { ElMessage } from 'element-plus';
// 前端生成二维码组件
import QrcodeGenerator from '@/components/QrcodeGenerator';
// store
import useSettingsStore from '@/store/modules/settings';
// 拖拽组件
import DraggableDiv from '@/components/Draggable';
// 图片裁剪组件
import CropImage from '@/components/CropImage';
// 生成截图并返回 Base64 图片 URL
import { generateScreenshotImage } from '@/utils/screenshot';
// base64转成bold上传到服务器
import { base64ToBlob } from '@/utils';
// 控制裁剪弹窗的显示与隐藏
const isCropperVisible = ref(false);
// store
const store = useSettingsStore();
const emit = defineEmits(['update:dialogVisible']);
// 接收来自父组件的 dialogVisible 作为 props
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    required: true,
  },
  form: {
    type: Object,
    default: () => {},
  },
});

// 创建一个本地的 reactive 表单副本
const dialogForm = reactive({
  ...props.form, // 初始化时将父组件传入的 form 赋值给本地表单
});
onMounted(() => {
  console.log(props.form, '图片为啥不显示');
});
// 是否为新水印图
// const isNewWater = ref(false);
// 加载
const loading = ref(false);
// 生成截图 Base64 图片 URL
const htmlImg = ref('');
// 生成截图框
const htmlCanvas = ref(null);
// 获取logo
const LOGO_URL = ref('');
// 拖拽container
const container = ref(null);
// 前端生成二维码内容
const qrText = ref(store.h5addr);
// 上传类型
const uploadType = ref('water');
// 上传二维码ref
const uploadRef = ref(null);
// 上传二维参数
const upload = reactive({
  // 上传二维码弹窗变量
  open: false,
  // 弹出层标题
  title: '上传图片',
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Token: getToken() },
  // 上传的地址
  url: '/dev-api/api/index/imageUpload',
  imgurl: '',
  // 是否禁用上传
  disabled: true,
});
// 定义背景图片的 URL
const backgroundImageUrl = ref('');
// 动态设置背景图片的 CSS 样式
const backgroundImageStyle = computed(() => ({
  backgroundImage: `url(${backgroundImageUrl.value})`,
  backgroundSize: 'cover', // 让背景图适应元素大小
  backgroundPosition: 'center', // 背景图居中
  position: 'absolute',
  top: 0,
}));
// 监听 props.form 的变化，并同步更新 dialogForm
watch(
  () => props.form,
  (newForm) => {
    Object.assign(dialogForm, newForm); // 更新本地表单副本
  },
  { deep: true, immediate: true } // 深度监听并立即执行
);
// 监听 dialogForm 变化
watch(
  () => dialogForm.watermark,
  (newVal) => {
    console.log(newVal, '监听水印', store.watermark);

    if (newVal) {
      backgroundImageUrl.value = newVal; // 设置为父组件传来的 watermark
    } else {
      backgroundImageUrl.value = store.watermark; // 使用 store 中的 watermark
    }
  },
  { immediate: true } // 立即执行一次，以确保初始状态
);
watch(
  () => dialogForm.logo,
  (newVal) => {
    if (newVal) {
      LOGO_URL.value = newVal; // 设置为父组件传来的 logo
    } else {
      LOGO_URL.value = store.menuIcon.logo; // 使用 store 中的 logo
    }
  },
  { immediate: true, deep: true } // 立即执行一次，以确保初始状态
);
// 上传二维码
const customUploadRequest = async ({
  file,
  onSuccess,
  onError,
  onProgress,
}) => {
  // 文件大小限制为 5MB
  const maxFileSize = 5 * 1024 * 1024; // 5MB

  // 判断文件大小是否超过 5MB
  if (file.size > maxFileSize) {
    ElMessage({
      message: '文件大小不能超过 5MB',
      type: 'error',
    });
    return; // 阻止上传
  }

  // 调用封装的 uploadFile 函数来处理上传逻辑
  uploadFile(
    file,
    upload.url, // 上传的 URL
    upload.headers, // 自定义请求头
    (progressEvent) => {
      // 进度回调
      onProgress({ percent: Number(progressEvent.percent) }); // 进度回调
    },
    (response) => {
      onSuccess(response); // 上传成功的回调
      upload.imgurl = response.data.url; // 假设返回的图片 URL 存储在 response.data.url
      upload.disabled = false; // 上传成功后允许再次上传
    },
    (error) => {
      onError(error); // 上传失败的回调
    }
  );
};

// 关闭弹窗的函数，触发 emit，通知父组件更新 dialogVisible
const closeDialog = () => {
  emit('update:dialogVisible', false);
};

// 关闭上传二维码弹窗
const closeUploadDialog = () => {
  initDialog();
};
// 生成的总图
const downloadImg = ref('');
const saveEdit = async (type) => {
  loading.value = true;
  try {
    // 生成 Base64 图片-预览图-总图
    const baseImgUrl = await generateScreenshotImage({
      htmlCanvas: htmlCanvas.value,
      LOGO_URL: LOGO_URL.value,
      dialogForm,
      htmlImg: htmlImg.value,
    });

    // 提取第一个 Base64 图片并转换为 Blob
    const mimeType1 = baseImgUrl.match(/data:(.*?);base64/)[1]; // 提取 MIME 类型
    const imageBlob1 = base64ToBlob(baseImgUrl, mimeType1); // Blob for first image (screenshot)

    // 检查 LOGO_URL 是否为 HTTP 地址，如果不是，则转换为 Blob
    let imageBlob2;
    const isLogoUrlBase64 = !LOGO_URL.value.startsWith('http');
    if (isLogoUrlBase64) {
      const mimeType2 = LOGO_URL.value.match(/data:(.*?);base64/)[1]; // 提取 LOGO 的 MIME 类型
      imageBlob2 = base64ToBlob(LOGO_URL.value, mimeType2); // Blob for second image (logo)
    }

    // 并行上传 Blob，并解构返回结果
    const [response1, response2] = await Promise.all([
      uploadFile(
        imageBlob1,
        upload.url,
        upload.headers,
        // onProgress 回调，处理上传进度
        (progress) => {
          console.log('progress:', progress);
        },
        // onSuccess 回调，处理成功的响应
        (data) => {
          downloadImg.value = data.data.url;
        },
        // onError 回调，处理失败
        (error) => {
          console.log('error:', error);
        }
      ),
      // logo地址
      isLogoUrlBase64
        ? uploadFile(
            imageBlob2,
            upload.url,
            upload.headers,
            // onProgress 回调，处理上传进度
            (progress) => {
              console.log('progress:', progress);
            },
            // onSuccess 回调，处理成功的响应
            (data) => {
              LOGO_URL.value = data.data.url;
            },
            // onError 回调，处理失败
            (error) => {
              console.log('error:', error);
            }
          )
        : Promise.resolve({ url: LOGO_URL.value }), // 如果 LOGO 是 HTTP 链接，直接返回该 URL
    ]);
    console.log('response2:', response2);

    // 如果是预览
    if (type === 'preview') {
      window.open(response1.data.url, '_blank'); // 打开预览图
    } else {
      // 保存编辑
      const params = {
        watermark: backgroundImageUrl.value, // 水印图地址
        show_id: dialogForm.show_id, // 显示设置
        id: dialogForm.id ? dialogForm.id : '0', // 编辑新增
        contacts: dialogForm.contacts, // 联系人
        phone: dialogForm.phone, // 联系电话
        address: dialogForm.address, // 联系地址
        qrcode_url: qrText.value, // 二维码链接
        qrcode: dialogForm.qrcode, // 二维码图片地址
        mg_id: dialogForm.mg_id, // id
        download: downloadImg.value, // 生成的图片地址-//总图
        logo: LOGO_URL.value, // logo地址
      };

      try {
        // 把 await 放到这里
        await saveMarketingGallery(params);
        ElMessage.success('保存成功');
        emit('update:dialogVisible', false);
      } catch (error) {
        console.log('error:', error);
        ElMessage.error('保存失败');
      }
    }
  } catch (error) {
    console.log('error:', error);
    ElMessage.error('生成图片失败');
  } finally {
    loading.value = false; // 关闭加载状态
  }
};
// 下载图片
const downloadImage = async (type) => {
  loading.value = true;
  try {
    const baseImgUrl = await generateScreenshotImage({
      htmlCanvas: htmlCanvas.value,
      LOGO_URL: LOGO_URL.value,
      dialogForm,
      htmlImg: htmlImg.value,
    });
    let a = document.createElement('a');
    // 图片：水印图
    if (type === 'water') {
      // 如果是水印图片，直接使用 base64 的数据
      a.href = baseImgUrl;
    } else {
      // 如果是原图，使用 fetch 来获取远程图片并转换为 Blob
      const response = await fetch(dialogForm.img_url);
      const blob = await response.blob(); // 将图片转化为 Blob
      const objectURL = URL.createObjectURL(blob); // 创建 Blob URL
      a.href = objectURL; // 强制下载 Blob 数据
    }
    a.download = dialogForm.mg_name; // 设置下载的文件名
    a.click(); // 触发下载
    // 清理 Blob URL，防止内存泄漏
    if (type !== 'water') {
      URL.revokeObjectURL(a.href);
    }
    await addDownloadNum({
      type: '1',
      id: dialogForm.mg_id,
    });
  } catch (error) {
    console.log(error);
  }
  loading.value = false;
};

// 上传二维码提交
const submit = () => {
  initDialog();
  if (uploadType.value == 'code') {
    dialogForm.qrcode = upload.imgurl;
  } else {
    backgroundImageUrl.value = upload.imgurl;
  }
  console.log(uploadType.value, backgroundImageUrl.value, '图片水印');
};
// 打开上传二维码
const openUpload = (type) => {
  uploadType.value = type;
  upload.open = true;
};
// 初始化弹窗
const initDialog = () => {
  uploadRef.value.clearFiles();
  upload.open = false;
  upload.disabled = true;
};
// 删除二维码
const deleteQrcode = () => {
  ElMessageBox.confirm('删除后将恢复成默认二维码。是否确定删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      dialogForm.qrcode = null;
      ElMessage({
        type: 'success',
        message: '删除成功',
      });
    })
    .catch(() => {});
};
// 编辑/上传logo
const updateLogo = () => {
  isCropperVisible.value = true;
};
// 删除logo
const delLogo = () => {
  LOGO_URL.value = '';
};
// 裁剪图片的地址
const crop = (val) => {
  LOGO_URL.value = val;
};
// 删除水印
const deleteWatermark = () => {
  ElMessageBox.confirm('删除后将恢复成默认水印。是否确定删除？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // isNewWater.value = false
      backgroundImageUrl.value = store.watermark;
      ElMessage({
        type: 'success',
        message: '删除成功',
      });
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog__footer) {
  display: flex;
  justify-content: center;
}

:deep(.el-overlay-dialog) {
  overflow: unset;
}

:deep(.el-dialog) {
  max-height: 680px;
}

.main {
  display: flex;

  .leftdiv {
    width: 287px;
    height: 513px;
    padding: 6px;
    overflow-y: hidden;
    background: #f7f8fa;

    .capture-wrapper {
      background: #fff;
      width: 100%;
      height: 100%;
      position: relative;

      .capture-body {
        max-height: calc(100% - 100px);
        overflow-y: auto;

        img {
          width: 100%;
          min-height: 380px;
        }
      }

      /* 添加 position: relative 来确保子元素可以使用绝对定位 */
      .zone-logo {
        width: 160px;
        height: 50px;
        line-height: 50px;
        background: #ecf5ff;
        border: 1px dashed #b3d8ff;
        color: #409eff;
        text-align: center;
      }

      .logo-img {
        width: 86px;
        height: 28px;
        display: flex;
        align-items: center;
        max-width: 160px;
        max-height: 50px;
        position: absolute;
        /* 设置为绝对定位 */
        top: 10px;
        /* 根据需要调整定位 */
        left: 10px;
        /* 根据需要调整定位 */
        border: 1px dashed transparent;
        cursor: move;
      }

      .drag-edit-box {
        width: 80px;
        font-size: 12px;
        height: 21px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        border-radius: 4px;
        background-color: #303133;
        margin-top: 10px;
        position: absolute;
        /* 确保编辑框也固定 */
        top: 50px;
        /* 根据需要调整 */
        left: 10px;
        /* 根据需要调整 */

        span {
          cursor: pointer;
        }
      }

      .bottom-info {
        // height: 120px;
        background: #fff;
        width: 100%;
        // position: sticky;
        // bottom: 0;
        display: flex;
        padding: 6px;
        justify-content: end;

        .user-info {
          flex: 1;

          .info-box {
            display: flex;
          }

          .text {
            width: 74px;
          }

          .title {
            display: flex;
            color: #4e5969;
            font-size: 14px;
            word-break: break-all;
            width: 110px;
            display: inline-block;
            vertical-align: text-top;
            margin-bottom: 5px;
          }

          .address {
            max-height: 40px;
            overflow: hidden;
            overflow-y: scroll;
            /* 始终显示垂直滚动条 */
            overflow-x: hidden;
            scrollbar-width: thin;
            /* 设置滚动条为细窄样式 */
            scrollbar-color: #888 #f1f1f1;
            /* 设置滚动条颜色 */
          }
        }

        .code-box {
          justify-content: flex-end;
          display: flex;
          width: 100%;

          &.img {
            width: 46px;
            height: 46px;
          }

          :deep(canvas) {
            margin: 0 !important;
          }
        }
      }

      .watermark {
        width: 100%;
        height: 100%;
      }
    }
  }

  .rightdiv {
    flex: 1;
    padding-left: 10px;
    margin-top: -10px;

    .market-form {
      height: 540px;
      padding-bottom: 15px;
      overflow-y: auto;

      .qrcode-upload {
        border: none;
        background: none;
        color: #165dff;
        cursor: pointer;
        padding-top: 0;
        padding-right: 12px;

        &:last-child {
          padding-left: 0;
          margin: 0;
        }
      }

      :deep(.el-form-item__label) {
        font-weight: 400;
        color: #86909c;
      }

      :deep(.el-textarea__inner) {
        min-height: 114px !important;
        line-height: 23px;
        padding: 12px 17px 8px 16px;
      }
    }

    .footer {
      display: flex;
      align-items: center;
      gap: 12px;
      padding-left: 39px;

      .el-icon {
        font-size: 20px;
        color: #1c5dff;
        cursor: pointer;
      }

      .tooltip-container {
        position: relative;
        display: inline-block;
        cursor: pointer;
      }

      .tooltip-text {
        visibility: hidden;
        background-color: #333;
        color: #fff;
        text-align: center;
        padding: 5px 10px;
        border-radius: 4px;
        position: absolute;
        z-index: 1;
        bottom: 141%;
        left: 50%;
        transform: translateX(-50%);
        opacity: 0;
        transition: opacity 0.3s;
        white-space: nowrap;
        /* 避免内容换行 */
        min-width: 60px;
        /* 设置最小宽度，根据需要调整 */
      }

      .tooltip-container:hover .tooltip-text {
        visibility: visible;
        opacity: 1;
      }

      .tooltip-text::after {
        content: '';
        position: absolute;
        top: 100%;
        /* 箭头显示在提示框底部 */
        left: 50%;
        margin-left: -5px;
        border-width: 5px;
        border-style: solid;
        border-color: #333 transparent transparent transparent;
      }
    }
  }

  :deep(.dis > .el-input__wrapper) {
    box-shadow: none;
    background: none;
  }

  :deep(.dis > .el-input__wrapper > .el-input__inner) {
    -webkit-text-fill-color: #4e5969;
    font-size: 14px;
  }

  em {
    color: #165dff;
    font-style: normal;
  }

  :deep(.el-message-box__header) {
    display: flex;
  }
}

.el-loading-mask {
  display: flex !important;
  align-items: center;
  justify-content: center;
}
</style>
